package Tracker.http;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

public class Handler implements HttpHandler {
	public void handle(HttpExchange t) throws IOException {

		Socket socket = new Socket("127.0.0.1", 9001);
		
		t.getResponseHeaders().add("Content-Type", "application/json");
		t.sendResponseHeaders(200, 0);
		
		// Request (From Browser)
		PrintWriter sockOut = new PrintWriter(socket.getOutputStream(), true);
		InputStreamReader httpIn = new InputStreamReader(t.getRequestBody());
		char[] reqChar = new char[1024];
		
		httpIn.read(reqChar);
		String request = new String(reqChar);
		
		System.out.println("Client --> " + request);
		sockOut.println(request.trim());
		
		// Response (To Browser)
		PrintWriter httpOut = new PrintWriter(t.getResponseBody());
		InputStreamReader sockIn = new InputStreamReader(socket.getInputStream());
		char[] resChar = new char[1024];
		
		sockIn.read(resChar);
		String response = new String(resChar);

		System.out.println("Server --> (" + response.length() + ") " + response);
		httpOut.println(response.trim());
		
		httpOut.close();
		System.out.println("HTTP Response Closed");
		socket.close();
		System.out.println("TCP Socket Closed");
		
	}
}
